package com.goldsign.pay.common.util;

import com.goldsign.pay.common.string.StringUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.Properties;
import java.util.Set;

/**从属性文件中获取配置属性值的工具类*/
public class GcPropertyPlaceholderConfigurer
		extends PropertyPlaceholderConfigurer {
	private static Properties ctxProperties = new Properties();

	@Override
	protected void processProperties(
			ConfigurableListableBeanFactory beanFactoryToProcess,
			Properties props) throws BeansException {
		// TODO Auto-generated method stub
		super.processProperties(beanFactoryToProcess, props);
		Set<Object> keySet = props.keySet();
		String keyStr = null;
		for(Object key : keySet){
			keyStr = (String)key;
			ctxProperties.put(keyStr, props.getProperty(keyStr));
		}
	}
	/**从Spring加载的属性文件中获取配置属性值*/
	public static String getContextProperty(String key){
		return ctxProperties.getProperty(key);
	}
	
	/**
	 * 从Spring加载的属性文件中获取配置属性值
	 * @param key 属性文件配置中的key
	 * @param defaultVal 属性文件配置为空时默认的值
	 * @return
	 */
	public static String getContextProperty(String key, String defaultVal){
		String val = ctxProperties.getProperty(key);
		return StringUtil.isEmpty(val, defaultVal);
	}
	
	/**
	 * 追加上下文属性配置,如果key已存在,则追加失败,抛出异常
	 * @param key
	 * @param value
	 * @throws Exception
	 */
	public static void appendContextProperty(String key, String value) throws Exception{
		if (ctxProperties.get(key) != null) {
			throw new Exception("配置错误,已存在的键:" + key);
		}
		ctxProperties.put(key, value);
	}
	
}
